package com.power.powercash.report;

import java.awt.Dimension;
import java.awt.Point;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author f6036477
 */
public class HorizontalResizeManager implements PropertyChangeListener {

	private List<HorizontalResizePanel> panels;


	public HorizontalResizeManager() {
		panels = new LinkedList<HorizontalResizePanel>();
	}


	public void add(HorizontalResizePanel panel) {
		if(panel == null) return;
		panels.add(panel);
		panel.addPropertyChangeListener(this);
	}


	public int getNumPanels() {
		return panels.size();
	}


	public void remove(HorizontalResizePanel panel) {
		if(panel == null) return;
		panels.remove(panel);
		panel.removePropertyChangeListener(this);
	}


	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if(evt.getOldValue() instanceof HorizontalResizePanel
				&& evt.getPropertyName().equals("size")
				&& panels.size() > 1) {

			HorizontalResizePanel hp =
					(HorizontalResizePanel) evt.getOldValue();

			int totaldif = (Integer) evt.getNewValue();
			if(totaldif == 0) return;

			int dif = totaldif / (panels.size()-1);
			int max = panels.size();
			if(dif == 0) {
				max = 1;
				dif = (totaldif > 0 ? 1 : -1);
			} else {
				dif += 1;
			}
			int idxsrc = 0;

			for(int i = 0; i < panels.size(); i++) {
				HorizontalResizePanel p = panels.get(i);
				Point loc = p.getLocation();

				if(p == hp) {
					idxsrc = i;
				}
				else if(loc.x > hp.getLocation().x) {
					Dimension size = p.getSize();
					dif = totaldif / (panels.size() - (idxsrc+1)) +1;

					Dimension nd;
					if(i == idxsrc+1) {
						p.setLocation(loc.x + totaldif+1, loc.y);
						nd = new Dimension(
								size.width - dif, size.height);
					} else {
						int mod = totaldif % (panels.size() - (idxsrc+1));
						p.setLocation(loc.x + totaldif-dif+1, loc.y);
						nd = new Dimension(
								size.width - dif+1-mod, size.height);
					}

					p.setPreferredSize(nd);
					p.setSize(nd);

					if(dif == 1 || dif == -1) break;
				}
			}//for
		}
	}

}
